package vn.cuhanh;

import java.io.IOException;
import java.util.ArrayList;

import org.json.JSONException;
import org.json.JSONObject;

import vn.cuhanh.utils.CuhanhDao;
import vn.cuhanh.utils.HelperFunc;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources.NotFoundException;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;

public class ChangeAvatarActivity extends Activity {
	private int currentAvatarNumber;
	private int selectedPosition = 0;
	private ArrayList<String> avatarNumbers = new ArrayList<String>();
	private ArrayList<Bitmap> bitmaps = new ArrayList<Bitmap>();
	ChangeAvatarGridAdapter adapter;
	
	private ProgressDialog progress;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.change_avatar);
		currentAvatarNumber = getIntent().getExtras().getInt("vn.cuhanh.changeAvatarActivity.currentAvatarNumber");
		String[] tmp = getResources().getStringArray(R.array.avatar_number);
		for(int i = 0; i < tmp.length; i++) {
			if(Integer.parseInt(tmp[i]) == currentAvatarNumber) {
				continue;
			}
			avatarNumbers.add(tmp[i]);
			try {
				bitmaps.add(HelperFunc.getBitmapFromAsset(this, 
						getResources().getString(R.string.avatar_file_name).replace("number", tmp[i])));
			} catch (NotFoundException e) {
				// TODO Auto-generated catch block
				HelperFunc.readStackTrace(e);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				HelperFunc.readStackTrace(e);
			} catch (Exception e) {
				HelperFunc.readStackTrace(e);
			}
		}
		adapter = new ChangeAvatarGridAdapter(this, R.id.txtDndScore);
		((GridView)findViewById(R.id.change_avatar_grid)).setAdapter(adapter);
		Button btnSave = (Button) findViewById(R.id.change_avatar_btn_save);
		btnSave.setText(R.string.save);
		btnSave.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				v.setClickable(false);
				progress = ProgressDialog.show(ChangeAvatarActivity.this, null, getResources().getString(R.string.award_progress_dialog_message));
				Thread thread = new Thread(new Runnable() {
					@Override
					public void run() {
						// TODO Auto-generated method stub
						String response = HelperFunc.getDataFromSv(
								ChangeAvatarActivity.this.getResources().getString(R.string.updateAvatarNumberUrl)
								.replace("avatar_number", avatarNumbers.get(selectedPosition))
								.replace("user_name", MainActivity.username));
						runOnUiThread(new Runnable() {
							public void run() {
								if(progress != null) {
									progress.dismiss();
								}
							}
						});
						if(response == null) {
							runOnUiThread(new Runnable() {
								@Override
								public void run() {
									// TODO Auto-generated method stub
									HelperFunc.showSimpleAlertDialog(ChangeAvatarActivity.this, null, getResources().getString(R.string.no_network_2), getResources().getString(R.string.bt_ok_title), null, null, null, true);
								}
							});
							return;
						}
						try {
							JSONObject jsonRes = new JSONObject(response);
							int result = jsonRes.getInt("result");
							if(result == 0) {
								runOnUiThread(new Runnable() {
									@Override
									public void run() {
										// TODO Auto-generated method stub
										HelperFunc.showSimpleAlertDialog(ChangeAvatarActivity.this, null, getResources().getString(R.string.unknown_error), getResources().getString(R.string.bt_ok_title), null, null, null, true);
									}
								});
								return;
							}
							if(result == 1) {
								CuhanhDao.updateAvatarNumber(ChangeAvatarActivity.this, MainActivity.username, Integer.parseInt(avatarNumbers.get(selectedPosition)));
								MainActivity.userAccount.setAvatarNumber(Integer.parseInt(avatarNumbers.get(selectedPosition)));
								runOnUiThread(new Runnable() {
									
									@Override
									public void run() {
										// TODO Auto-generated method stub
										HelperFunc.showSimpleAlertDialog(ChangeAvatarActivity.this, null, getResources().getString(R.string.change_avatar_success), getResources().getString(R.string.bt_ok_title), new DialogInterface.OnClickListener() {
											@Override
											public void onClick(DialogInterface dialog, int which) {
												// TODO Auto-generated method stub
												Intent intent = new Intent(ChangeAvatarActivity.this, GameDetailActivity.class);
												startActivity(intent);
											}
										}, null, null, true);
									}
								});
							}
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							HelperFunc.readStackTrace(e);
						}
					}
				});
				thread.start();
			}
		});
		Button btnClose = (Button) findViewById(R.id.change_avatar_btn_close);
		btnClose.setText(R.string.close);
//		btnClose.setBackground(getResources().getDrawable(R.drawable.btn_grey_bg));
		btnClose.setBackgroundResource(R.drawable.btn_grey_bg);
		btnClose.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				onBackPressed();
			}
		});
	}
	
	public class ChangeAvatarGridAdapter extends ArrayAdapter<String> {

		public ChangeAvatarGridAdapter(Context context, int textViewResourceId) {
			super(context, textViewResourceId);
			// TODO Auto-generated constructor stub
		}
		
		@Override
		public int getCount() {
			return avatarNumbers.size();
		}
		
		@Override
		public View getView(final int position, View v, ViewGroup parent) {
			if(v == null) {
				LayoutInflater inflater = (LayoutInflater)getContext().getSystemService(LAYOUT_INFLATER_SERVICE);
				v = inflater.inflate(R.layout.change_avatar_grid_item, null);
			}
			try {
				((ImageView)v.findViewById(R.id.change_avatar_grid_item_image)).setImageBitmap(bitmaps.get(position));
			} catch (Exception e) {
				// TODO: handle exception
				HelperFunc.readStackTrace(e);
			}
			if(selectedPosition == position) {
				v.setBackgroundColor(0xFFBD3A00);
			} else {
				v.setBackgroundColor(0xFFF0F0F0);
			}
			v.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View arg0) {
					// TODO Auto-generated method stub
					selectedPosition = position;
					adapter.notifyDataSetChanged();
				}
			});
			return v;
		}
	}
}
